﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
namespace Admin.NET.Application;

/// <summary>
/// 计划分类服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class PlanTypeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<PlanType> _planTypeRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public PlanTypeService(SqlSugarRepository<PlanType> planTypeRep, ISqlSugarClient sqlSugarClient)
    {
        _planTypeRep = planTypeRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 获取分类列表
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取分类列表")]
    [ApiDescriptionSettings(Name = "List"), HttpGet]
    public async Task<List<PlanTypeOutput>> List()
    {
        var res = _planTypeRep.AsQueryable()
            .Where(u => u.Status == StatusEnum.Enable)
            .Select<PlanTypeOutput>();
        return await res.ToListAsync();
    }

    /// <summary>
    /// 分页查询计划分类 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询计划分类")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<PlanTypeOutput>> Page(PagePlanTypeInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _planTypeRep.AsQueryable()
            .OrderBy(x => x.OrderNo)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Name.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            .Select<PlanTypeOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取计划分类详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取计划分类详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<PlanType> Detail([FromQuery] QueryByIdPlanTypeInput input)
    {
        return await _planTypeRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加计划分类 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加计划分类")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddPlanTypeInput input)
    {
        var entity = input.Adapt<PlanType>();
        if (await _planTypeRep.IsAnyAsync(u => u.Name != null && u.Name == input.Name)) throw Oops.Oh("分类已存在");
        return await _planTypeRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新计划分类 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新计划分类")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdatePlanTypeInput input)
    {
        if (await _planTypeRep.IsAnyAsync(u => u.Id != input.Id && u.Name != null && u.Name == input.Name)) throw Oops.Oh("分类已存在");
        var entity = input.Adapt<PlanType>();
        await _planTypeRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除计划分类 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除计划分类")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeletePlanTypeInput input)
    {
        var entity = await _planTypeRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _planTypeRep.FakeDeleteAsync(entity);   //假删除
        //await _planTypeRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除计划分类 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除计划分类")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeletePlanTypeInput> input)
    {
        var exp = Expressionable.Create<PlanType>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _planTypeRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _planTypeRep.FakeDeleteAsync(list);   //假删除
        //return await _planTypeRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 设置计划分类状态 🚫
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置计划分类状态")]
    [ApiDescriptionSettings(Name = "SetStatus"), HttpPost]
    public async Task SetPlanTypeStatus(SetPlanTypeStatusInput input)
    {
        await _planTypeRep.AsUpdateable().SetColumns(u => u.Status, input.Status).Where(u => u.Id == input.Id).ExecuteCommandAsync();
    }
    
    /// <summary>
    /// 导出计划分类记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出计划分类记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PagePlanTypeInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportPlanTypeOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "计划分类导出记录");
    }
    
    /// <summary>
    /// 下载计划分类数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载计划分类数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportPlanTypeOutput>(), "计划分类导入模板");
    }
    
    private static readonly object _planTypeImportLock = new object();
    /// <summary>
    /// 导入计划分类记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入计划分类记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_planTypeImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportPlanTypeInput, PlanType>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        return true;
                    }).Adapt<List<PlanType>>();
                    
                    var storageable = _planTypeRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Name), "分类不能为空")
                        .SplitError(it => it.Item.Name?.Length > 32, "分类长度不能超过32个字符")
                        .WhereColumns(it => new { it.Name })
                        .SplitInsert(it=> !it.Any())
                        .SplitUpdate(it=> it.Any())
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Name,
                        it.OrderNo,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
